//
//  ChatContactMgr.m
//  WxSdk
//
//  Created by fusuwei on 14-9-18.
//  Copyright (c) 2014年 网信金融集团. All rights reserved.
//

#import "ChatContactMgr.h"
#include "PublicMacros.h"
#include "EPublicMacros.h"
#import "Utility.h"
#import "UcfgroupXMPPManger.h"

static BOOL initReadOnce = YES;

@implementation ChatContactMgr

+(NSString *)getDbPathName
{
    NSString *userId = [UcfgroupXMPPManger sharedInstance].logRegWxUserObject.UserId;
    if (initReadOnce && (userId == nil)) {
        initReadOnce = NO;
        userId = [[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_ID];
    }
    NSString *fileName = [self truncateNSString:userId To:kXMPPmyDomain];
    
    NSString *isFilePathName = [NSString stringWithFormat:@"%@/%@",DATABASE_PATH,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:isFilePathName]) {
        [fileManager createDirectoryAtPath:isFilePathName withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *filePathName = [NSString stringWithFormat:@"%@/%@%@",DATABASE_PATH,fileName,@"/wxChatIM.db"];
    return filePathName;
}
//将某一字符从开始位置截取到指定字符处
+ (NSString *)truncateNSString:(NSString *)srcStr To:(NSString *)toStr
{
    if (srcStr == nil) {
        return nil;
    }
    NSRange range = [srcStr rangeOfString:toStr];
    NSString *str = [srcStr substringToIndex:range.location];
    return str;
}

//check ChatContact table is create in db
+(BOOL)checkChatContactTableCreatedInDb:(YY_FMDatabase *)db
{
    BOOL worked = NO;
    NSString *createTable=@"CREATE  TABLE  IF NOT EXISTS ChatContact ('ContactId' VARCHAR NOT NULL UNIQUE, 'ContactName' VARCHAR)";
    worked = [db executeUpdate:createTable];
    if (!worked) {
        WXLog(@"Create ChatContact's table resutl %d",worked);
    }
    
    createTable=@"CREATE  TABLE  IF NOT EXISTS ChatContactRequest ('ContactId' VARCHAR NOT NULL UNIQUE, 'ContactName' VARCHAR, 'ContactState' VARCHAR, 'ContactText' VARCHAR, 'ContactIsSend' INT default 0)";
    worked = [db executeUpdate:createTable];
    if (!worked) {
        WXLog(@"Create ChatContactRequest's table resutl %d",worked);
    }
    
    FMDBQuickCheck(worked);
    return worked;
}

//查找ContactId是否存在
+(BOOL)isFindTheContactId:(NSString*)ContactId isExistInTable:(NSString*)tableName
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return YES;
    };
    
    YY_FMResultSet *rs = nil;
    if ([tableName isEqualToString:@"ChatContact"]) {
        rs = [db executeQuery:@"select count(*) from ChatContact where ContactId=?",ContactId];
    }
    else if ([tableName isEqualToString:@"ChatContactRequest"])
    {
        rs = [db executeQuery:@"select count(*) from ChatContactRequest where ContactId=?",ContactId];
    }
    else
    {
        NSAssert(NO, @"Don't find the tableName");
    }
    
    while ([rs next]) {
        int count= [rs intForColumnIndex:0];
        
        if (count!=0){
            [rs close];
            return YES;
        }else
        {
            [rs close];
            return NO;
        }
    };
    [rs close];
    return YES;
}

//保存联系人到ChatContact表中
+(BOOL)saveChatContactDic:(NSMutableDictionary*)ContactDic
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatContactTableCreatedInDb:db];
    
    NSString *ContactId = [ContactDic objectForKey:@"ContactId"];
    NSString *ContactName = [ContactDic objectForKey:@"ContactName"];
    
    //如果在表中已经存在，就更新此联系人的ContactName
    if([self isFindTheContactId:ContactId isExistInTable:@"ChatContact"])
    {
        BOOL retb = [self saveUpdateContactId:ContactId fieldName:@"ContactName" value:ContactName];
        return retb;
    }
    
    //否则插入此条消息
    NSString *insertStr=@"INSERT INTO ChatContact ('ContactId','ContactName') VALUES (?,?)";
    BOOL worked = [db executeUpdate:insertStr,ContactId,
                   ContactName];
    
    //FMDBQuickCheck(worked);
    
    [db close];
        
    return worked;
}

//更新指定NSString字段
+(BOOL)saveUpdateContactId:(NSString*)UserId fieldName:(NSString*)fieldName value:(NSString*)value
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatContactTableCreatedInDb:db];
    
    NSString *updateStr = [NSString stringWithFormat:@"update ChatContact set %@=? where UserId=?",fieldName];
    
    BOOL worked = [db executeUpdate:updateStr,value, UserId];
    
    [db close];
    
    //发送收到联系人更新通知
    [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPBuddyListChangeNotifaction object:nil];
    
    return worked;
}

//更新指定NSInteger字段
+(BOOL)saveUpdateContactId:(NSString*)ContactId fieldName:(NSString*)fieldName valueInt:(NSInteger)value
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatContactTableCreatedInDb:db];
    
    NSString *updateStr = [NSString stringWithFormat:@"update ChatContact set %@=? where ContactId=?",fieldName];
    
    BOOL worked = [db executeUpdate:updateStr,[NSNumber numberWithInteger:value], ContactId];
    
    //FMDBQuickCheck(worked);
    
    [db close];
    
    //    //发送收到新聊天消息通知
    //    [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPRecvChatMsgNotifaction object:nil];
    
    return worked;
}

//删除某个联系人
+ (BOOL)deleteContactId:(NSString *)ContactId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    }
    
    NSString *deleteStr = [NSString stringWithFormat:@"DELETE FROM ChatContact where ContactId=?"];
    
    BOOL worked = [db executeUpdate:deleteStr, ContactId];
    
    [db close];
    
    return worked;
}

//获取某个联系人Id对应的Name
+ (NSString *)fetchNameByContactId:(NSString *)ContactId
{
    NSString *findName = nil;
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return @"未知";
    }
    
    NSString *queryString = @"select * from ChatContact where ContactId=?";
    YY_FMResultSet *rs=[db executeQuery:queryString,ContactId];
    while ([rs next]) {
        findName = [rs stringForColumn:@"ContactName"];
    }
    
    [rs close];
    
    return findName;
}

//获取ChatContact表某个联系人的对象
+ (ChatContact *)fetchChatContactByContactId:(NSString *)ContactId
{
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"fetchChatContactByContactId 数据打开失败");
        return nil;
    }
    
    [self checkChatContactTableCreatedInDb:db];
    
    ChatContact *contactReq = nil;
    
    NSString *queryString = @"select * from ChatContact where ContactId=?";
    YY_FMResultSet *rs=[db executeQuery:queryString,ContactId];
    while ([rs next]) {
        contactReq = [[ChatContact alloc] init];
        contactReq.ContactId = [rs stringForColumn:@"ContactId"];
        contactReq.ContactName = [rs stringForColumn:@"ContactName"];
        contactReq.ContactHeadPicUrl = @"";
    }
    
    [rs close];
    
    return contactReq;
}

//更新备注信息
+ (BOOL)updateTheContact:(NSString *)ContactId ContactName:(NSString *)ContactName
{
    return [self saveUpdateContactId:ContactId fieldName:@"ContactName" value:ContactName];
}

//获取得到所有联系人列表
+ (NSMutableArray *)getAllContactList
{
    NSMutableArray *contactList = [NSMutableArray array];
    
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"getAllContactList 数据打开失败");
        return contactList;
    }
    
    [self checkChatContactTableCreatedInDb:db];
    
    NSString *queryString = @"select * from ChatContact";
    YY_FMResultSet *rs=[db executeQuery:queryString];
    while ([rs next]) {
        ChatContact *contact = [[ChatContact alloc] init];
        
        contact.ContactId = [Utility getBareContactId:[rs stringForColumn:@"ContactId"]];
        contact.ContactName = [rs stringForColumn:@"ContactName"];
        contact.ContactHeadPicUrl = [NSString stringWithFormat:@"%@%@%@",[[UcfgroupXMPPManger sharedInstance] getFileServer],@"file/get_small_avatar/",contact.ContactId];
        [contactList addObject:contact];
    }
    
    [rs close];
    
    return  contactList;
}

//保存 请求添加联系人 和 被请求添加联系人 到ChatContactRequest表中
+(BOOL)saveChatContactRequestDic:(NSMutableDictionary*)ContactDic
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatContactTableCreatedInDb:db];
    
    NSString *ContactId = [ContactDic objectForKey:@"ContactId"];
    NSString *ContactName = [ContactDic objectForKey:@"ContactName"];
    NSString *ContactState = [ContactDic objectForKey:@"ContactState"];
    NSString *ContactText = [ContactDic objectForKey:@"ContactText"];
    NSNumber *ContactIsSend = [ContactDic objectForKey:@"ContactIsSend"];
    
    //如果在表中已经存在，就更新此联系人的ContactName
    if([self isFindTheContactId:ContactId isExistInTable:@"ChatContactRequest"])
    {
        //更新此条消息
        NSString *insertStr=@"update ChatContactRequest set ContactName=?,ContactState=?,ContactText=?,ContactIsSend=? where ContactId=?";
        BOOL worked = [db executeUpdate:insertStr,
                       ContactName,
                       ContactState,
                       ContactText,
                       ContactIsSend,
                       ContactId];
        
        [db close];
        return worked;
    }
    
    //否则插入此条消息
    NSString *insertStr=@"INSERT INTO ChatContactRequest ('ContactId','ContactName','ContactState','ContactText','ContactIsSend') VALUES (?,?,?,?,?)";
    BOOL worked = [db executeUpdate:insertStr,ContactId,
                   ContactName,
                   ContactState,
                   ContactText,
                   ContactIsSend];
    
    [db close];
        
    return worked;
}

//更新ChatContactRequest表指定NSString字段
+(BOOL)saveUpdateChatContactRequestContactId:(NSString*)ContactId fieldName:(NSString*)fieldName value:(NSString*)value
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatContactTableCreatedInDb:db];
    
    NSString *updateStr = [NSString stringWithFormat:@"update ChatContactRequest set %@=? where ContactId=?",fieldName];
    
    BOOL worked = [db executeUpdate:updateStr,value, ContactId];
    
    [db close];
    
    return worked;
}

//获取ChatContactRequest表某个联系人请求或被请求的对象
+ (ChatContactRequest *)fetchChatRequestByContactId:(NSString *)ContactId
{
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"fetchChatRequestByContactId 数据打开失败");
        return nil;
    }
    
    [self checkChatContactTableCreatedInDb:db];
    
    ChatContactRequest *contactReq = [[ChatContactRequest alloc] init];
    
    NSString *queryString = @"select * from ChatContactRequest where ContactId=?";
    YY_FMResultSet *rs=[db executeQuery:queryString,ContactId];
    while ([rs next]) {
        contactReq.ContactId = [rs stringForColumn:@"ContactId"];
        contactReq.ContactName = [rs stringForColumn:@"ContactName"];
        contactReq.ContactState = [rs stringForColumn:@"ContactState"];
        contactReq.ContactText = [rs stringForColumn:@"ContactText"];
        contactReq.ContactIsSend = [rs intForColumn:@"ContactIsSend"];
    }
    
    [rs close];
    
    return contactReq;
}

//删除ChatContactRequest中某个联系人请求或被请求 （当删除某个联系人时，同步删除该表中的对应数据）
+ (BOOL)deleteChatContactRequestContactId:(NSString *)ContactId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    }
    
    NSString *deleteStr = [NSString stringWithFormat:@"DELETE FROM ChatContactRequest where ContactId=?"];
    
    BOOL worked = [db executeUpdate:deleteStr, ContactId];
    
    [db close];
    
    return worked;
}

//获取我已经发出请求添加的和接收到的邀请 好友列表
+ (NSMutableArray *)getAllInviteOrInvitedContacts
{
    NSMutableArray *contactList = [NSMutableArray array];
    
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"getAllContactList 数据打开失败");
        return contactList;
    }
    
    [self checkChatContactTableCreatedInDb:db];
    
    //NSString *queryString = @"select * from ChatContactRequest where ContactState='sendReq' or ContactState='receiveReq'";
    NSString *queryString = @"select * from ChatContactRequest";
    YY_FMResultSet *rs=[db executeQuery:queryString];
    while ([rs next]) {
        ChatContactRequest *contactReq = [[ChatContactRequest alloc] init];
        contactReq.ContactId = [rs stringForColumn:@"ContactId"];
        contactReq.ContactName = [rs stringForColumn:@"ContactName"];
        contactReq.ContactState = [rs stringForColumn:@"ContactState"];
        contactReq.ContactText = [rs stringForColumn:@"ContactText"];
        contactReq.ContactIsSend = [rs intForColumn:@"ContactIsSend"];
        [contactList addObject:contactReq];
    }
    
    [rs close];
    
    return  contactList;
}
#pragma mark  -------------------------------哈哈哈哈哈哈或
//check ChatContact table is create in db
+(BOOL)checkContactMemTableCreatedInDb:(YY_FMDatabase *)db
{
    BOOL worked = NO;
    NSString *createTable=@"CREATE  TABLE  IF NOT EXISTS ContactMem ('ContactId' VARCHAR NOT NULL UNIQUE, 'headPath' VARCHAR, 'userName' VARCHAR )";
    worked = [db executeUpdate:createTable];
    if (!worked) {
        WXLog(@"Create ChatContact's table resutl %d",worked);
    }
    
    FMDBQuickCheck(worked);
    return worked;
}

//查找ContactId是否存在
+(BOOL)isFindTheContactMem:(NSString*)ContactId isExistInTable:(NSString*)tableName
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return YES;
    };
    
    YY_FMResultSet *rs = nil;
    if ([tableName isEqualToString:@"ContactMem"]) {
        rs = [db executeQuery:@"select count(*) from ContactMem where ContactId=?",ContactId];
    }
    else
    {
        NSAssert(NO, @"Don't find the tableName");
    }
    
    while ([rs next]) {
        int count= [rs intForColumnIndex:0];
        
        if (count!=0){
            [rs close];
            return YES;
        }else
        {
            [rs close];
            return NO;
        }
    };
    [rs close];
    return YES;
}

+(BOOL)saveContactMemModel:(ContactMemModel*)ContactDic{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkContactMemTableCreatedInDb:db];
    
    NSString *ContactId = ContactDic.ContactId;
    NSString *ContactName = ContactDic.userName;
    NSString *HeadUrl = ContactDic.headPath;
    
    //如果在表中已经存在，就更新此联系人的ContactName
    if([self isFindTheContactMem:ContactId isExistInTable:@"ContactMem"])
    {
        //更新此条消息
        NSString *insertStr=@"update ContactMem set userName=?, headPath=? where ContactId=?";
        BOOL worked = [db executeUpdate:insertStr,
                       ContactName,
                       HeadUrl,
                       ContactId];
        [db close];
        return worked;
    }
    
    //否则插入此条消息
    NSString *insertStr=@"INSERT INTO ContactMem ('ContactId','userName','headPath') VALUES (?,?,?)";
    BOOL worked = [db executeUpdate:insertStr,ContactId,
                   ContactName,
                   HeadUrl];
    
    [db close];
    
    return worked;
}
//获取得到所有联系人列表
+ (NSMutableArray *)getAllContactMemList
{
    NSMutableArray *contactList = [NSMutableArray array];
    
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"ContactMem 数据打开失败");
        return contactList;
    }
    
    [self checkContactMemTableCreatedInDb:db];
    
    NSString *queryString = @"select * from ContactMem";
    YY_FMResultSet *rs=[db executeQuery:queryString];
    while ([rs next]) {
        ContactMemModel *contact = [[ContactMemModel alloc] init];
        
        contact.ContactId = [Utility getBareContactId:[rs stringForColumn:@"ContactId"]];
        contact.userName = [rs stringForColumn:@"userName"];
        contact.headPath = [rs stringForColumn:@"headPath"];
        [contactList addObject:contact];
    }
    
    [rs close];
    
    return  contactList;
}
//获取某个联系人Id对应的Name headurl
+ (NSDictionary *)fetchContactMemNameByContactId:(NSString *)ContactId
{
    NSMutableDictionary *tempdic = [NSMutableDictionary dictionary];
    NSString *headPath;
    NSString *userName;
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return @{};
    }
    
    NSString *queryString = @"select * from ContactMem where ContactId=?";
    YY_FMResultSet *rs=[db executeQuery:queryString,ContactId];
    while ([rs next]) {
        userName = [rs stringForColumn:@"userName"]?:@"";
        headPath = [rs stringForColumn:@"headPath"]?:@"";
    }
    [tempdic  setValue:userName forKey:@"userName"];
    [tempdic  setValue:headPath forKey:@"headPath"];
    [rs close];
    
    return tempdic;
}

@end
